package core.development.h2.example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.tools.Server;

public class H2Test {
	private Server server;
	private String port = "9080";
	private String dbDir = "./h2db/sample";
	private String user = "sa";
	private String password = "";
	public void startServer() {
		try {
			System.out.println("正在启动h2...");
			server = Server.createTcpServer(new String[] { "-tcpPort", port })
					.start();
		} catch (SQLException e) {
			System.out.println("启动h2出错：" + e.toString());
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	public void stopServer() {
		if (server != null) {
			System.out.println("正在关闭h2...");
			server.stop();
			System.out.println("关闭成功.");
		}
	}
	public void useH2() {
		try {
			Class.forName("org.h2.Driver");
			Connection conn = DriverManager.getConnection("jdbc:h2:file:D:/myJavaWorkSpace/JavaHi/WebRoot/WEB-INF/h2db/sample",
					user, password);
			Statement stat = conn.createStatement();
			// insert data
			//stat.execute("DROP TABLE IF EXISTS TEST");
//			stat.execute("create table T_PROJECT" +
//					"(" +
//					"ID         VARCHAR2(50) not null," +
//					"TITLE      VARCHAR2(500)," +
//					"CONTENT    VARCHAR2(3000)," +
//					"REMARK     VARCHAR2(3000)," +
//					"STATUS     NUMBER," +
//					"TYPE       NUMBER," +
//					"CREATETIME DATE," +
//					"WORKER     VARCHAR2(50)" +
//					")");
			// use data
			ResultSet result = stat.executeQuery("select title from t_project ");
			int i = 1;
			while (result.next()) {
				System.out.println(i++ + ":" + result.getString("title"));
			}
			result.close();
			stat.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		H2Test h2 = new H2Test();
		h2.startServer();
		h2.useH2();
		h2.stopServer();
		System.out.println("==END==");
	}
}

